﻿@using HP.HPTRIM.Service;
@using ServiceStack.Razor;

@inherits TrimViewPage<DocuSignPlugin.DSSigningResponse>
@{
    if (this.Model.ViewUrl != null)
    {
        this.ViewBag.HideMenu = true;
    }
}

@if (this.Model.ViewUrl == null)
{ 
    <div class="banner">
        <h2>Signing</h2>
    </div>
    <div class="details-pane" style="width:500px">
        @Html.Partial("DSLoginForm")
    </div>
}
else
{
    @* An iframe so that we can load the DocuSign page inside the IFRAME and then trigger the  script below to undo the
        Record checkout if the user navigates away without completing.*@
    <iframe id="signing-frame" src="@this.Model.ViewUrl" style="border:none; margin-left:10px; display:none;"></iframe>
}

@section scripts {
    <script>
    var resizePreview = function () {
        var signingFrame = $('#signing-frame');

        if (signingFrame) {
            signingFrame.show();
            signingFrame.css("visibility", "visible");

            var height = $(window).height() - ($('#signing-frame').offset().top + 5);
            signingFrame.height(height);

            var width = $(window).width() - 10;

            if (width > 630) {
                width = width - ($('#leftcolumn').width());
            }
            signingFrame.width(width);
        }
    }

    $(function () {
        $(window).on("load resize", function () {
            resizePreview();
        });


        // this code calls the Undocheckout whenever the page onloads.  This means that if the user aborts part way through
        // the Record checkout will be undone.  We ignore errors as this also fires of the process completes successfully, in which
        // case UndoCheckout will throw an exception as the Record is not checked out.
        $(window).on("beforeunload", function () {
            var signingFrame = $('#signing-frame');

            if (signingFrame) {
                var formData = {
                    'Uri': @this.Model.Uri,
                    'ActionsToCall': [{
                        '__type': 'HP.HPTRIM.ServiceModel.UndoCheckout'
                        , 'UndoCheckoutComments': 'DocuSign signing aborted.'
                    }]
                }

                $.ajax({
                    url: '@Url.Content("~/Record")',
                        type: 'POST',
                        contentType: 'application/x-www-form-urlencoded',
                        data: 'Uri=' + @this.Model.Uri + '&ServiceActions=UndoCheckout'

                    })
                    .done(function (response, statusText) {
                        console.log('Checkout undone.')
                    })
                .fail(function (xhr) {
                    console.log('failed')
                });

                }
            })
        });
    </script>
}